#include "dialogs/chatwindow.h"

#include <QtCore>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QScrollBar>

ChatWindow::ChatWindow(const QString& login, const QString& phrase, QWidget* parent) : QDialog(parent, Qt::Window)
{
  this->login = login;

  setWindowTitle(tr("Chat with user [%1]").arg(login));

  chatOutput = new QTextEdit(this);
  chatOutput->setReadOnly(true);
  chatOutput->setLineWrapMode( QTextEdit::WidgetWidth );

  tellButton = new QPushButton("tell", this);

  phraseEdit = new QLineEdit(this);

  QHBoxLayout* editLayout = new QHBoxLayout;
  editLayout->addWidget( phraseEdit );
  editLayout->addWidget( tellButton );

  QVBoxLayout* mainLayout = new QVBoxLayout;
  mainLayout->addWidget(chatOutput);
  mainLayout->addLayout(editLayout);
  setLayout( mainLayout );

  phraseEdit->setFocus();  

  if ( !phrase.isNull() )
    addPhrase(QString("> %1").arg(phrase));

  connect( phraseEdit, SIGNAL(returnPressed()), this, SLOT(tellPhrase()) );
  connect( tellButton, SIGNAL(clicked()), this, SLOT(tellPhrase()) );
}

void ChatWindow::addPhrase( const QString& phrase )
{
  chatOutput->moveCursor( QTextCursor::End );
  chatOutput->insertPlainText( phrase );
  chatOutput->moveCursor( QTextCursor::End );
  chatOutput->insertPlainText( "\n" );
  QScrollBar* scrollBar = chatOutput->verticalScrollBar();
  scrollBar->setValue( scrollBar->maximum() );
}

void ChatWindow::tellPhrase()
{
  if ( phraseEdit->text().length() ) {
    addPhrase(QString("< %1").arg( phraseEdit->text() ));
    QString phrase( QString("tell %1 %2").arg(login).arg(phraseEdit->text()) );
    phraseEdit->clear();
    emit sendCommand( phrase );
  }
  phraseEdit->setFocus();
}
